# Create your views here.
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm as RegisterForm
from django.core.cache import cache
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from myweb import Constans
from myweb.interest.models import Category,Interest

@login_required
def interest(request):
    if request.method == 'POST':
        follows = request.POST.getlist('follow')
        Interest.objects.update_user_follows(request.user.id,follows)
        cache.delete(Constans.USER_INTEREST + "#" + str(request.user.id))
    categories = cache.get(Constans.CATEGORIES)
    if categories == None:
        categories = Category.objects.all()
        cache.set(Constans.CATEGORIES, categories) 
    context = RequestContext(request)
    context['categories'] = categories
    
    return render_to_response('interest.html', context)
    
        
@login_required
def home(request):
    return render_to_response('home.html',RequestContext(request))        
        
def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid ():
            user = form.save()
            user.backend = 'django.contrib.auth.backends.ModelBackend'
            auth.login(request, user)
            return HttpResponseRedirect('/member/interest')
    else:
        form = RegisterForm()
    return render_to_response('register.html', {'form':form}, context_instance=RequestContext(request))

